<template>
  <a-card :bordered="false">
    <!--  #####################查询条件###################  -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="商户订单号">
              <a-input v-model="queryParam.outTradeNo" placeholder="商户订单号"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="交易单号">
              <a-input v-model="queryParam.transactionId" placeholder="交易单号"/>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="客户(商圈)">
                <a-select v-model="queryParam.parentCode" placeholder='请选择' allowClear @change="handleProvinceChange">
                  <a-select-option v-for="item in customers" :key="item.code">{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="商户">
                <a-select v-model="queryParam.merchantCode" placeholder='请选择' allowClear @change="handleMerchantChange">
                  <a-select-option v-for="item in merchants" :key="item.code">{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="商品">
                <a-select v-model="queryParam.productNo" placeholder='请选择' allowClear>
                  <a-select-option v-for="item in coupons" :key="item.stockId">{{item.stockName}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="领取状态">
                <a-select v-model="queryParam.sendStatus" placeholder='请选择' allowClear>
                  <a-select-option value="1">未领取</a-select-option>
                  <a-select-option value="2">已领取</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="开始时间">
                <a-date-picker format="YYYY-MM-DD" v-model="queryParam.beginTime" style="width: 100%" placeholder="开始时间"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="结束时间">
                <a-date-picker format="YYYY-MM-DD" v-model="queryParam.endTime" style="width: 100%" placeholder="结束时间"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons"
                  :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button v-action:query type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--  #####################查询条件###################  -->

    <!--  #####################操作###################  -->
    <div class="table-operator">
      <a-button type="primary" :loading="loading" @click="exportExcell()">导出EXCEL</a-button>
    </div>
    <!--  #####################操作###################  -->
    <!--<div class="table-operator">
      &lt;!&ndash;<span>订单总数：<a-tag color="blue">{{statistics.ordercount}}</a-tag></span>&ndash;&gt;
      <span>总金额：<a-tag color="cyan">￥{{statistics.orderAmount}}元</a-tag></span>
      &lt;!&ndash;<span>已付订单：<a-tag color="green">{{statistics.paycount}}</a-tag></span>&ndash;&gt;
      <span>已付金额：<a-tag color="green">￥{{statistics.payAmount}}元</a-tag></span>
      &lt;!&ndash;<span>未付订单：<a-tag color="#f50">{{statistics.uncount}}</a-tag></span>&ndash;&gt;
      <span>未付金额：<a-tag color="pink">￥{{statistics.unpayAmount}}元</a-tag></span>
      <span>支付率：<a-tag color="purple">{{successRate}}%</a-tag></span>
    </div>-->
    <!--  #####################表格###################  -->
    <s-table
      ref="table"
      :columns="columns"
      :data="loadData"
      bordered
    >
      <span slot="amount" slot-scope="text, record">
        <b>{{record.transactionId ? '￥' : '' }}{{record.transactionId ? text * 0.01 : text }}</b>
      </span>
      <a-tag slot="status" slot-scope="text, record" :color="text | statusColorFilter">
        {{text | statusFilter}}
      </a-tag>
      <a-tag slot="sendStatus" slot-scope="text, record" :color="text | sendColorFilter">
        {{text | sendFilter}}
      </a-tag>
      <span slot="action" slot-scope="text, record">
        <!--<template>
          <a v-action:query v-if="record.notifyStatus==2" @click="doNotice(record)">重新通知</a>
        </template>-->
      </span>
    </s-table>
    <!--  #####################表格###################  -->

  </a-card>
</template>

<script>
  import moment from 'moment'
  import { STable } from '@/components'
  import { selectAgentTree } from '@/api/system/company'
  import { selectAllCustomer } from '@/api/shop/customer'
  import { selectAllMerchant } from '@/api/shop/merchant'
  import { selectAllCoupon } from '@/api/shop/coupon'
  import { selectPage, doNotice, exportExcel } from '@/api/shop/trade'

  const statusMap = {
    0: {
      status: '',
      text: '未支付'
    },
    1: {
      status: 'cyan',
      text: '已支付'
    }
  }
  const notityMap = {
    1: {
      status: 'red',
      text: '未领取'
    },
    2: {
      status: '#2db7f5',
      text: '已领取'
    },
  }

  export default {
    name: 'menuList',
    components: {
      STable
    },
    data () {
      return {
        mdl: {},
        // 高级搜索 展开/关闭
        advanced: false,
        loading: false,
        // 查询参数
        queryParam: {},
        customers: [],
        merchants: [],
        coupons: [],
        treeData: [],
        //统计信息
        statistics: {
          orderCount: 0,
          orderAmount: 0,
          payCount: 0,
          payAmount: 0,
          unpayCount: 0,
          unpayAmount: 0
        },
        successRate: '',
        // 表头
        columns: [
          {
            title: '商品名称',
            dataIndex: 'productName'
          },
          {
            title: '用户昵称',
            dataIndex: 'nickName'
          },
          {
            title: '客户订单号',
            dataIndex: 'outTradeNo'
          },
          {
            title: '金额',
            dataIndex: 'price',
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '订单创建时间',
            dataIndex: 'createdTime'
          },
          {
            title: '支付状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' }
          },
          {
            title: '领取状态',
            dataIndex: 'sendStatus',
            scopedSlots: { customRender: 'sendStatus' }
          },
          {
            title: '交易单号',
            dataIndex: 'transactionId'
          },
          // {
          //   title: '操作',
          //   dataIndex: 'action',
          //   width: '150px',
          //   scopedSlots: { customRender: 'action' }
          // }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return selectPage(Object.assign(parameter, this.queryParam))
            .then(res => {
              this.statistics = res.result.statistics
              //this.successRate = Math.round((parseFloat((this.statistics.payCount) / this.statistics.orderCount).toFixed(2) * 100))
              return res.result.pageInfo
            })
        }
      }
    },
    filters: {
      statusFilter (status) {
        return statusMap[status].text
      },
      statusColorFilter (status) {
        return statusMap[status].status
      },
      sendFilter (status) {
        return notityMap[status].text
      },
      sendColorFilter (status) {
        return notityMap[status].status
      }
    },
    created () {
      // const params = { 'isCode': true }
      // selectAgentTree(params).then(res => {
      //   if (res.code === 200) {
      //     this.treeData = res.result
      //   }
      // })
      selectAllCustomer().then(res => {
        let that = this
        this.customers = res.result
        //初始化客户默认选中
        //this.customerId = this.customers[0].id
        const params = { 'customerCode': this.customers[0].code }
        selectAllMerchant(params).then(res1 => {
          that.merchants = res1.result
        })
      })
    },
    methods: {
      doNotice (row) {
        doNotice(row.outTradeNo).then(res => {
          if (res.code === 200) {
            this.$message.info(res.message)
            this.$refs.table.refresh()
          }
        })
      },
      handleProvinceChange (value) {
        const params = { 'customerCode': value }
        selectAllMerchant(params).then(res1 => {
          this.merchants = res1.result
        })
      },
      handleMerchantChange (value) {
        const params = { 'merchantCode': value }
        selectAllCoupon(params).then(res1 => {
          this.coupons = res1.result
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      exportExcell() {
        const _this = this
        this.$confirm({
          title: '警告',
          content: `确认导出当前查询条件下的所有交易记录？`,
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            _this.loading = true
            let parameter= {}
            exportExcel(Object.assign(parameter, _this.queryParam)).then(res => {
              _this.loading = false
              const link = document.createElement('a')
              let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
              link.style.display = 'none'
              link.href = URL.createObjectURL(blob);
              let num = ''
              for (let i = 0; i < 10; i++) {
                num += Math.ceil(Math.random() * 10)
              }
              link.setAttribute('download', '订单记录.xlsx')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
            })
          },
          onCancel() {
            console.log('Cancel')
          }
        })
      },
    }
  }
</script>
